import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @作者 ： lvlintao666 @时间 ： 2024/8/17 @测试点 :测试MetaData.getPrimaryKeys(), getIndexInfo() 获取分区表的pk,index信息
 */
public class Opengauss_Function_JDBC_DatabaseMetaData_Case0001 {

    private static Connection openGaussConnection;
	private static String schema;
	private static String table;

    public static void main(String[] args) {
        if (args.length < 6) {
            System.out.print("need para: host:ip,dbname,username,password");
            return;
        }
		String url = "jdbc:postgresql://" + args[0] + "/" + args[1] + "?LoggerLevel=OFF";
		schema = args[4];
		table = args[5];
        try {
            openGaussConnection = DriverManager.getConnection(url, args[2], args[3]);
            testMetadata();
            openGaussConnection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void testMetadata() throws SQLException{
		DatabaseMetaData metaData = openGaussConnection.getMetaData();
        String catalog = "";
		ResultSet rs = metaData.getPrimaryKeys(catalog, schema, table);
        System.out.println("--------get primaryKey begin");
        while (rs.next()){
            String columnName = rs.getString(4);
            int columnIndex = rs.getInt(5);
            System.out.println(String.format("columnIndex: %s , columnName: %s", columnIndex, columnName));
        }
        System.out.println("--------get primaryKey end");

        try (ResultSet rs1 = metaData.getIndexInfo(catalog, schema, table, true, true)){
            System.out.println("--------get index info begin");
            while(rs1.next()){
                final String indexName = rs1.getString(6);
                final String columnName = rs1.getString(9);
                System.out.println(String.format("columnIndex: %s , columnName: %s", indexName, columnName));
            }
            System.out.println("--------get index info end");
        }
    }
}